<script setup>
import {nextTick, onMounted, onUnmounted, ref, computed, reactive, watch} from 'vue'
import ResultItem from "./components/ResultItem.vue";
import SettingsPanel from "./components/SettingsPanel.vue";
import {EventsOn} from '../wailsjs/runtime'
import {WindowHide} from "../wailsjs/runtime/runtime.js";
import {
  GetAppIcon, 
  GetAppIconByPath,
  LaunchApp, 
  SearchKeyWords, 
  UpdateAppUsage, 
  GetFavoriteApps, 
  GetRecentApps,
  GetMostUsedApps,
  ToggleFavorite,
  AddCustomWebApp
} from "../wailsjs/go/system/App.js";

const inputText = ref('')
const searchResults = ref([])
const inputBox = ref('')
const iconSrc = ref('')
const showSettings = ref(false)
const showAddWebAppModal = ref(false)

// 应用状态
const appState = reactive({
  isLoading: false
})

// 新网页应用表单数据
const newWebApp = reactive({
  name: '',
  url: '',
  icon: ''
})

// 获取应用图标
const getAppIcon = async (app) => {
  if (!app || !app.icon) {
    return iconSrc.value
  }
  
  // 如果是网络图标，直接返回
  if (app.icon.startsWith('http')) {
    return app.icon
  }
  
  // 如果已经是base64格式，直接返回
  if (app.icon.startsWith('data:')) {
    return app.icon
  }
  
  // 尝试通过后端API获取图标
  try {
    const iconData = await GetAppIconByPath(app.icon)
    return iconData || iconSrc.value
  } catch (error) {
    console.error('获取应用图标失败:', error)
    return iconSrc.value
  }
}

// 启动应用程序
const launchApp = async (app) => {
  try {
    if (app.appType === 'web') {
      await window.open(app.path)
    } else {
      await LaunchApp(app.path)
    }
    // 更新应用使用统计
    await UpdateAppUsage(app.path)
  } catch (error) {
    console.error('启动应用失败:', error)
    // 可以显示错误信息给用户
  } finally {
    WindowHide()
  }
}

// 防抖定时器
let searchTimer = null

// 监听输入变化进行搜索
const handleInput = async (event) => {
  const keyword = event?.target?.value || inputText.value
  console.log('输入事件触发:', keyword)
  
  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  
  // 如果输入为空，立即清空结果
  if (!keyword || keyword.trim() === '') {
    searchResults.value = []
    return
  }
  
  // 根据关键词长度动态调整防抖延迟
  const trimmedKeyword = keyword.trim()
  let debounceDelay = 150 // 默认150ms
  
  if (trimmedKeyword.length === 1) {
    debounceDelay = 200 // 单字符稍微长一点
  } else if (trimmedKeyword.length >= 3) {
    debounceDelay = 100 // 长关键词更快响应
  }
  
  // 设置防抖延迟
  searchTimer = setTimeout(async () => {
    appState.isLoading = true
    try {
      console.log('开始搜索:', trimmedKeyword)
      const results = await SearchKeyWords(trimmedKeyword)
      console.log('搜索结果:', results)
      console.log('搜索结果数量:', results ? results.length : 0)
      
      // 预加载图标数据
      if (results && results.length > 0) {
        const resultsWithIcons = await Promise.all(
          results.map(async (app) => {
            try {
              const iconData = await getAppIcon(app)
              return { ...app, iconData }
            } catch (error) {
              console.error('加载图标失败:', app.name, error)
              return { ...app, iconData: iconSrc.value }
            }
          })
        )
        searchResults.value = resultsWithIcons
      } else {
        searchResults.value = results || []
      }
    } catch (error) {
      console.error('搜索失败:', error)
      searchResults.value = []
    } finally {
      appState.isLoading = false
    }
  }, debounceDelay)
}

// 监听输入框值变化
const handleInputChange = () => {
  console.log('输入框值变化:', inputText.value)
  handleInput()
}

// 切换收藏状态
const toggleFavorite = async (app) => {
  const isFavorite = await ToggleFavorite(app.path)
  // 更新本地状态
  const appIndex = searchResults.value.findIndex(a => a.path === app.path)
  if (appIndex !== -1) {
    searchResults.value[appIndex].isFavorite = isFavorite
  }
}

// 添加自定义网页应用
const addCustomWebApp = async () => {
  if (!newWebApp.name || !newWebApp.url) {
    return
  }
  
  const iconUrl = newWebApp.icon || `https://www.google.com/s2/favicons?domain=${new URL(newWebApp.url).hostname}`
  await AddCustomWebApp(newWebApp.name, newWebApp.url, iconUrl)
  
  // 重置表单
  newWebApp.name = ''
  newWebApp.url = ''
  newWebApp.icon = ''
  showAddWebAppModal.value = false
  
  // 刷新搜索结果
  if (inputText.value) {
    handleInput()
  }
}

// 聚焦到输入框
const focusInput = async () => {
  await nextTick()
  if (inputBox.value) {
    inputBox.value.focus()
    // 选中所有文本（如果有的话）
    inputBox.value.select()
  }
}

const handleKeyDown = async (event) => {
  if (event.key === 'Escape') {
    if (showSettings.value) {
      showSettings.value = false
    } else if (inputText.value) {
      inputText.value = ''
      searchResults.value = []
    } else {
      WindowHide()
    }
  } else if (event.key === 'F1') {
    // 切换设置面板
    showSettings.value = !showSettings.value
  }
}

// 计算当前显示的应用列表
const displayedApps = computed(() => {
  console.log(`搜索结果数量: ${searchResults.value ? searchResults.value.length : 0}`, searchResults.value)
  return searchResults.value || []
})

// 监听输入文本变化
watch(inputText, (newValue, oldValue) => {
  console.log('Watch 监听到输入变化:', oldValue, '->', newValue)
  handleInputChange()
}, { immediate: false })

onMounted(async () => {
  // 监听窗口显示事件
  EventsOn("wails.window.show", () => {
    focusInput()
  })
  document.addEventListener('keydown', handleKeyDown)
  
  try {
    // 调用 Go 函数
    iconSrc.value = await GetAppIcon()
  } catch (error) {
    console.error('初始化失败:', error)
  }
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
})
</script>

<template>
  <a-layout>
    <a-layout-header>
      <a-input
          ref="inputBox"
          id="input-box"
          type="text"
          v-model="inputText"
          @input="handleInput"
          @keyup="handleInputChange"
          placeholder="输入关键字..."
          autocomplete="off"
      >
        <template #prefix>
          <div class="flex justify-center items-center rounded-full overflow-hidden w-9 h-9">
            <img :src="iconSrc" alt="icon" class="w-11 border-none">
          </div>
        </template>
        <template #suffix>
          <div class="flex gap-2">
            <a-button type="text" @click="showSettings = !showSettings" title="设置">
              <i class="i-carbon-settings"></i>
            </a-button>
          </div>
        </template>
      </a-input>
      
    </a-layout-header>
    
    <a-layout-content>
      <!-- 搜索结果区域 -->
      <div v-if="!appState.isLoading && displayedApps.length > 0" class="results-container">
        <ResultItem
            v-for="(app, index) in displayedApps"
            :key="index"
            :name="app.name"
            :icon="app.iconData || iconSrc"
            :is-favorite="app.isFavorite || false"
            :use-count="app.useCount || 0"
            :last-used="app.lastUsed"
            class="result-item-wrapper"
            @click="() => { inputText = app.name; searchResults = []; launchApp(app);}"
            @favorite="() => toggleFavorite(app)"
        />
      </div>
      
      <!-- 无结果提示 -->
      <div v-if="!appState.isLoading && displayedApps.length === 0" class="no-results">
        <p v-if="inputText">没有找到匹配的应用</p>
        <p v-else>输入关键字开始搜索</p>
        
        <!-- 添加自定义网页应用按钮 -->
        <a-button @click="showAddWebAppModal = true">
          添加网页应用
        </a-button>
      </div>
    </a-layout-content>
    
    <!-- 添加网页应用的模态框 -->
    <a-modal
      v-model:open="showAddWebAppModal"
      title="添加网页应用"
      @ok="addCustomWebApp"
      @cancel="showAddWebAppModal = false"
    >
      <a-form :model="newWebApp">
        <a-form-item label="名称">
          <a-input v-model:value="newWebApp.name" placeholder="请输入应用名称" />
        </a-form-item>
        <a-form-item label="URL">
          <a-input v-model:value="newWebApp.url" placeholder="请输入网页地址" />
        </a-form-item>
        <a-form-item label="图标URL (可选)">
          <a-input v-model:value="newWebApp.icon" placeholder="请输入图标地址" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-layout>
</template>

<style>
:root, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  background: transparent;
}

#input-box {
  width: 100%;
  padding: 10px 16px;
  font-size: 16px;
  border: none;
  border-radius: 6px;
  outline: none;
  background-color: rgba(255, 255, 255, 0.95);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

#input-box:focus {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

#input-box::placeholder {
  color: #999;
}

.results-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 10px;
  overflow-y: auto;
  max-height: 400px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
}

.no-results {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100px;
  color: #999;
}
</style>
